package models;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import Dao.DBConnect;

public class LoginModel   {
 
	private Boolean admin;
	private int id;
	private Boolean Sales;
	private String uname;




	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public Boolean getSales() {
		return Sales;
	}

	public void setSales(int data) {
		if (data == 2) {
		    this.Sales = Boolean.TRUE;
		}
		else {
			this.Sales = Boolean.FALSE;
		}

	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Boolean isSale() {
		return Sales;
	}

	public Boolean isAdmin() {
		return admin;
	}
	public void setAdmin(int admin) {
		if (admin == 1) {
			this.admin = Boolean.TRUE;
		}
		else {
			this.admin = Boolean.FALSE;
		}


	}

	public String hashit(String plaintext) throws NoSuchAlgorithmException {

		MessageDigest m = MessageDigest.getInstance("MD5");
		m.reset();
		m.update(plaintext.getBytes());
		byte[] digest = m.digest();
		BigInteger bigInt = new BigInteger(1,digest);
		String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
		while(hashtext.length() < 32 ){
			hashtext = "0"+hashtext;
		}
		return  hashtext;

	}


	public Boolean getCredentials(String username, String password){


        	String query = "SELECT * FROM mian_wang_users WHERE uname = ? and passwd = ?;";
            try(PreparedStatement stmt = DBConnect.getConnection().prepareStatement(query)) {
               stmt.setString(1, username);
               stmt.setString(2, hashit(password));
               ResultSet rs = stmt.executeQuery();
                if(rs.next()) { 
                 
                	setId(rs.getInt("id"));
                	setUname(rs.getString("uname"));
                	setAdmin(rs.getInt("role"));
                	setSales(rs.getInt("role"));
                	return true;
               	}

             }catch (SQLException | NoSuchAlgorithmException e) {
            	e.printStackTrace();   
             }
			return false;
    }

}//end class